#include "paraTable.h"
#include "globalDef.h"

#include "L610.h"
#include "string.h"
#include "fmc_flash.h"


ParaTable_typedef tagPara;


void initParaTable(void)
{
	memset(&tagPara, 0, sizeof(ParaTable_typedef));
	
}

/*
L610写参数表
写成功返回0，失败返回1,消息错误返回2
*/
uint32_t L610WriteParaTable(uint8_t * pDa, uint16_t len)
{
	
	uint8_t reDa1, reDa2;
	
	if (len != 950)
	{
		return 2;
	}
	
	//因为底层已经有写校验了，这里不再过多增加校验
	reDa1 = savePara1024WithAdr(FMC_PARA_TABLE_ADR, pDa, len);
	reDa2 = savePara1024WithAdr(FMC_PARA_TABLE2_ADR, pDa, len);
	
	if ( (reDa1 == 0x00) || (reDa2 == 0x00))
	{
		fillParaTableItem(pDa);
		return 0;
	}
	
	return 1;
	
}

//填写GD用到的几个参数，节省内存，暂时只用到电压
void fillParaTableItem(uint8_t * paraData)
{
	//暂时只返回电压值
	tagPara.valid = 1;
	tagPara.voltage = paraData[2] * 0x100 + paraData[3];
	
	//强制做个限制，如果设置错误，防止设备永远无法联网
	if (tagPara.voltage > 12000)
	{
		tagPara.voltage = 12000;
	}
	else if (tagPara.voltage < 7500)
	{
		tagPara.voltage = 7500;
	}
}

//每次开机读取一次参数表
uint32_t ReadParaTable(void)
{
	uint8_t reDa;
	uint8_t paraData[1200];
	
	reDa = readPara1024WithAdr(FMC_PARA_TABLE_ADR, paraData, 950);
	
	if (reDa != 0x00)
	{
		reDa = readPara1024WithAdr(FMC_PARA_TABLE2_ADR, paraData, 950);
		if (reDa == 0x00)
		{
			savePara1024WithAdr(FMC_PARA_TABLE2_ADR, paraData, 950);
		}
		else
		{
			return 1;
		}
	}
	
	fillParaTableItem(paraData);

	return 0;
}


//返回参数表是否有效，1有效，0无效
uint8_t getParaValid(void)
{
	return tagPara.valid;
}


uint16_t getParaItemVolt(void)
{
	if (tagPara.valid != 1)
	{
		return 1;
	}
	return tagPara.voltage;
}



/*
PC读参数表
返回0代表成功
*/
uint32_t ReadParaTable2Uart(uint8_t sel)
{
	uint8_t reDa;
	uint8_t paraData[1200];
	
	reDa = readPara1024WithAdr(FMC_PARA_TABLE_ADR, paraData, 950);
	
	if (reDa != 0x00)
	{
		reDa = readPara1024WithAdr(FMC_PARA_TABLE2_ADR, paraData, 950);
		if (reDa == 0x00)
		{
			savePara1024WithAdr(FMC_PARA_TABLE_ADR, paraData, 950);
		}
		else
		{
			return 1;
		}
	}
	
	send_general_package_to_uart(0x201B, paraData, 950, 0, 0, sel);
	
	
	return 0;
}


/*
PC读参数表
*/
uint32_t PCReadParaTable(void)
{
	return ReadParaTable2Uart(2);	
}


/*
L610读参数表
*/
uint32_t L610ReadParaTable(void)
{
	return ReadParaTable2Uart(0);	
	
}










